// 后端作品服务 - 使用PostgreSQL数据库
const database = require('../../src/config/database');
const pool = database.default || database.pool;

class ArticleService {
  // 创建作品
  async createArticle(articleData) {
    const { user_id, title, description, content, content_html, cover_image, status = 'draft' } = articleData;
    
    const query = `
      INSERT INTO articles (user_id, title, description, content, content_html, cover_image, status)
      VALUES ($1, $2, $3, $4, $5, $6, $7)
      RETURNING *
    `;
    
    const values = [user_id, title, description || null, JSON.stringify(content), content_html, cover_image, status];
    
    try {
      const result = await pool.query(query, values);
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('创建作品失败:', error);
      return {
        success: false,
        message: error.message || '创建作品失败'
      };
    }
  }

  // 更新作品
  async updateArticle(articleId, userId, articleData) {
    const { title, description, content, content_html, cover_image, status } = articleData;
    
    const query = `
      UPDATE articles 
      SET title = $1, description = $2, content = $3, content_html = $4, cover_image = $5, status = $6, updated_at = CURRENT_TIMESTAMP
      WHERE id = $7 AND user_id = $8
      RETURNING *
    `;
    
    const values = [title, description || null, JSON.stringify(content), content_html, cover_image, status, articleId, userId];
    
    try {
      const result = await pool.query(query, values);
      
      if (result.rows.length === 0) {
        return {
          success: false,
          message: '作品不存在或无权限修改'
        };
      }
      
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('更新作品失败:', error);
      return {
        success: false,
        message: error.message || '更新作品失败'
      };
    }
  }

  // 获取作品详情
  async getArticleById(articleId) {
    const query = `
      SELECT a.*, u.username, u.avatar_url
      FROM articles a
      LEFT JOIN users u ON a.user_id = u.id
      WHERE a.id = $1
    `;
    
    try {
      const result = await pool.query(query, [articleId]);
      
      if (result.rows.length === 0) {
        return {
          success: false,
          message: '作品不存在'
        };
      }
      
      const article = result.rows[0];
      // 解析JSON内容
      if (article.content) {
        try {
          // 如果content已经是对象，则不需要解析
          if (typeof article.content === 'string') {
            article.content = JSON.parse(article.content);
          }
        } catch (e) {
          console.warn('解析作品内容JSON失败:', e.message);
          // 如果解析失败，保持原始内容
        }
      }

      // 获取附件列表
      const attachmentsResult = await this.getArticleAttachments(articleId);
      article.attachments = attachmentsResult.success ? attachmentsResult.data : [];
      
      return {
        success: true,
        data: article
      };
    } catch (error) {
      console.error('获取作品失败:', error);
      return {
        success: false,
        message: error.message || '获取作品失败'
      };
    }
  }

  // 获取作品列表
  async getArticles(options = {}) {
    const { 
      page = 1, 
      limit = 10, 
      status = 'published', 
      user_id,
      search 
    } = options;
    
    const offset = (page - 1) * limit;
    
    let query = `
      SELECT a.id, a.title, a.content_html, a.cover_image, a.status, 
             a.view_count, a.created_at, a.updated_at,
             u.username, u.avatar_url
      FROM articles a
      LEFT JOIN users u ON a.user_id = u.id
      WHERE 1=1
    `;
    
    const values = [];
    let paramIndex = 1;
    
    if (status) {
      query += ` AND a.status = $${paramIndex}`;
      values.push(status);
      paramIndex++;
    }
    
    if (user_id) {
      query += ` AND a.user_id = $${paramIndex}`;
      values.push(user_id);
      paramIndex++;
    }
    
    if (search) {
      query += ` AND (a.title ILIKE $${paramIndex} OR a.content_html ILIKE $${paramIndex})`;
      values.push(`%${search}%`);
      paramIndex++;
    }
    
    query += ` ORDER BY a.created_at DESC LIMIT $${paramIndex} OFFSET $${paramIndex + 1}`;
    values.push(limit, offset);
    
    try {
      const result = await pool.query(query, values);
      
      // 获取总数
      let countQuery = `
        SELECT COUNT(*) as total
        FROM articles a
        WHERE 1=1
      `;
      
      const countValues = [];
      let countParamIndex = 1;
      
      if (status) {
        countQuery += ` AND a.status = $${countParamIndex}`;
        countValues.push(status);
        countParamIndex++;
      }
      
      if (user_id) {
        countQuery += ` AND a.user_id = $${countParamIndex}`;
        countValues.push(user_id);
        countParamIndex++;
      }
      
      if (search) {
        countQuery += ` AND (a.title ILIKE $${countParamIndex} OR a.content_html ILIKE $${countParamIndex})`;
        countValues.push(`%${search}%`);
      }
      
      const countResult = await pool.query(countQuery, countValues);
      const total = parseInt(countResult.rows[0].total);
      
      return {
        success: true,
        data: {
          articles: result.rows,
          pagination: {
            page,
            limit,
            total,
            totalPages: Math.ceil(total / limit)
          }
        }
      };
    } catch (error) {
      console.error('获取作品列表失败:', error);
      return {
        success: false,
        message: error.message || '获取作品列表失败'
      };
    }
  }

  // 删除作品
  async deleteArticle(articleId, userId) {
    const query = `
      DELETE FROM articles 
      WHERE id = $1 AND user_id = $2
      RETURNING *
    `;
    
    try {
      const result = await pool.query(query, [articleId, userId]);
      
      if (result.rows.length === 0) {
        return {
          success: false,
          message: '作品不存在或无权限删除'
        };
      }
      
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('删除作品失败:', error);
      return {
        success: false,
        message: error.message || '删除作品失败'
      };
    }
  }

  // 增加浏览量
  async incrementViewCount(articleId) {
    const query = `
      UPDATE articles 
      SET view_count = view_count + 1
      WHERE id = $1
      RETURNING view_count
    `;
    
    try {
      const result = await pool.query(query, [articleId]);
      return {
        success: true,
        data: { view_count: result.rows[0]?.view_count || 0 }
      };
    } catch (error) {
      console.error('更新浏览量失败:', error);
      return {
        success: false,
        message: '更新浏览量失败'
      };
    }
  }

  // 获取作品的附件列表
  async getArticleAttachments(articleId) {
    // 先尝试从media_files表查询
    let query = `
      SELECT 
        mf.id, mf.file_name, mf.original_name, mf.file_type, mf.file_size, 
        mf.file_url, mf.mime_type, mf.width, mf.height, mf.duration, mf.created_at,
        pc.pdf_url, pc.pdf_path, pc.conversion_status as pdf_status
      FROM media_files mf
      LEFT JOIN pdf_conversions pc ON mf.id = pc.original_file_id
      WHERE mf.article_id = $1
      ORDER BY mf.created_at ASC
    `;
    
    try {
      let result = await pool.query(query, [articleId]);
      
      // 如果media_files表中没有数据，尝试从attachments表查询（向后兼容）
      if (result.rows.length === 0) {
        query = `
          SELECT 
            att.id, att.file_name, att.original_name, att.file_type, att.file_size, 
            att.file_url, att.mime_type, att.width, att.height, att.duration, att.created_at,
            pc.pdf_url, pc.pdf_path, pc.conversion_status as pdf_status
          FROM attachments att
          LEFT JOIN pdf_conversions pc ON att.id = pc.original_file_id
          WHERE att.article_id = $1
          ORDER BY att.created_at ASC
        `;
        
        try {
          result = await pool.query(query, [articleId]);
        } catch (error) {
          console.warn('attachments表查询失败，可能不存在:', error.message);
          result = { rows: [] };
        }
      }
      
      // 处理附件数据，确保PDF信息正确
      const attachments = result.rows.map(attachment => ({
        ...attachment,
        // 如果是PDF文件且没有pdf_url，使用原文件URL作为PDF URL
        pdf_url: attachment.pdf_url || (attachment.mime_type === 'application/pdf' ? attachment.file_url : null),
        pdf_status: attachment.pdf_status || (attachment.mime_type === 'application/pdf' ? 'completed' : 'unknown')
      }));
      
      return {
        success: true,
        data: attachments
      };
    } catch (error) {
      console.error('获取附件列表失败:', error);
      return {
        success: false,
        message: '获取附件列表失败'
      };
    }
  }

  // 添加附件到作品
  async addAttachment(articleId, userId, fileData) {
    const { 
      file_name, 
      original_name, 
      file_type, 
      file_size, 
      file_url, 
      mime_type,
      width = null,
      height = null,
      duration = null
    } = fileData;
    
    const query = `
      INSERT INTO media_files (user_id, article_id, file_name, original_name, 
                              file_type, file_size, file_url, mime_type, width, height, duration)
      VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
      RETURNING *
    `;
    
    const values = [userId, articleId, file_name, original_name, file_type, 
                   file_size, file_url, mime_type, width, height, duration];
    
    try {
      const result = await pool.query(query, values);
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('添加附件失败:', error);
      return {
        success: false,
        message: '添加附件失败'
      };
    }
  }

  // 删除附件
  async deleteAttachment(attachmentId, userId) {
    const query = `
      DELETE FROM media_files 
      WHERE id = $1 AND user_id = $2
      RETURNING *
    `;
    
    try {
      const result = await pool.query(query, [attachmentId, userId]);
      
      if (result.rows.length === 0) {
        return {
          success: false,
          message: '附件不存在或无权限删除'
        };
      }
      
      return {
        success: true,
        data: result.rows[0]
      };
    } catch (error) {
      console.error('删除附件失败:', error);
      return {
        success: false,
        message: '删除附件失败'
      };
    }
  }
}

module.exports = new ArticleService();